#多轮对话
from openai import OpenAI

# 定义多轮对话方法
def multi_turn_conversation():
    # 初始化客户端
    client = OpenAI(base_url="http://localhost:11434/v1", api_key="any content")
    # 初始化对话历史
    chat_history = []
    # 启动对话循环
    while True:
        user_input = input("请输入你的消息：")
        if user_input.lower() in ["退出", "结束", "bye", "exit", "quit", "q"]:
            print("对话结束！")
            break

        # 更新对话历史（添加用户输入）
        chat_history.append({"role":"user", "content":user_input})
        # 调用模型回答问题
        try:
            chat_completion = client.chat.completions.create(
                model="qwen2.5:0.5b",
                messages=chat_history
            )
            # 获取最新回答
            model_response = chat_completion.choices[0]
            print("AI:", model_response.message.content)
            # 更新对话历史（添加模型回答）
            chat_history.append({"role":"assistant", "content":model_response.message.content})
        except Exception as e:
            print("发生错误：", e)
            break

if __name__ == '__main__':
    multi_turn_conversation()